package com.xzg.common.security;

import com.xzg.permission.entity.Permission;
import com.xzg.role.entity.Role;
import com.xzg.user.entity.User;
import com.xzg.user.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

public class MyRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;

    /**
     *@Author Ye
     *Date 2018-03-02 15:10
     *@Description 授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
//        String username = (String)principalCollection.getPrimaryPrincipal();
//        User user = userService.selectALLByUsername(username);
//        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
//        for(Role role :user.getRoleList()){
//            authorizationInfo.addRole(role.getRole());
//            for(Permission permission :role.getPermissionList()){
//                authorizationInfo.addStringPermission(permission.getPermission());
//            }
//        }
//        return authorizationInfo;
        return null;
    }

    /**
     *@Author Ye
     *Date 2018-03-02 15:10
     *@Description 认证登录
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;
        String username = usernamePasswordToken.getUsername();
        User user = userService.findUserByusername(username);
        if(user==null) {
            return null;
        } else {
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(),getName());
            SecurityUtils.getSubject().getSession().setAttribute("userinfo",user);
            return info;
        }
    }
}
